/*
 * @Author: ljk
 * @Date: 2023-07-26 17:41:44
 * @LastEditors: ljk
 * @LastEditTime: 2023-07-27 10:05:45
 * @Description: CP问题: 主函数
 */
#include "RingQueue.hpp"
#include "Task.hpp"

using namespace std;

const char* ops = "+-*/%";

void* consumerRoutine(void* args)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(args);
    while (true)
    {
        Task t;
        rq->pop(&t);
        t();
        cout << "consumer done, complicated process is " << t.formatRes() << endl;
        //sleep(1);
    }
}
void* productorRoutine(void* args)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(args);
    while (true)
    {
        //sleep(1);
        int x = rand() % 100;
        int y = rand() % 100;
        char op = ops[(x + y) % strlen(ops)];
        Task t(x, y, op);
        rq->push(t);
        cout << "productor done, producted process is " << t.formatArg() << endl;
        //sleep(1);
    }
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>();
    //单生产单消费
    // pthread_t c, p;
    // pthread_create(&c, nullptr, consumerRoutine, rq);
    // pthread_create(&p, nullptr, productorRoutine, rq);

    // pthread_join(c, nullptr);
    // pthread_join(p, nullptr);

    //多生产, 多消费, 该如何更改代码?
    //维护生产与生产, 消费与消费之间的互斥与同步
    //意义在哪里呢? 绝对不在从缓冲区中放入和拿取, 放前并发构建Task, 获取后多线程可以并发处理task, 因为这些操作没有枷锁
    pthread_t c[3], p[2];
    for (int i = 0; i < 3; i++)
        pthread_create(c + i, nullptr, consumerRoutine, rq);
    for (int i = 0; i < 2; i++)
        pthread_create(p + i, nullptr, productorRoutine, rq);
        
    for (int i = 0; i < 3; i++)
        pthread_join(c[i], nullptr);
    for (int i = 0; i < 2; i++)
        pthread_join(p[i], nullptr);

    delete rq;
    return 0;
}